package com.zrrd.blog.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.blog.api.entities.Comment;
import com.zrrd.blog.article.mapper.CommentMapper;
import com.zrrd.blog.article.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.blog.util.base.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论信息表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2023-08-07
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Override
    public Result findByArticleId(String articleId) {
        if(StringUtils.isEmpty(articleId)){
            return Result.error("文章id不能为空");
        }
        return Result.ok(baseMapper.findByArticleId(articleId));
    }

    @Override
    public Result deleteById(String id) {
        if(StringUtils.isEmpty(id)){
            return Result.error("评论id不能为空");
        }
        //将要删除的所有评论存储到一个集合中
        List<String> ids=new ArrayList<>();
        //将当前id存入集合
        ids.add(id);
        //通过递归查询出所有要删除的评论下的子评论
        this.getIds(ids,id);
        //批量删除
        baseMapper.deleteBatchIds(ids);
        return Result.ok();
    }

    public void getIds(List<String> ids, String parentId) {
        //查询子评论
        QueryWrapper<Comment> wrapper=new QueryWrapper<>();
        //select * from comment where parent_id=1001
        wrapper.eq("parent_id",parentId);
        //查询出所有该id下的评论
        List<Comment> commentList= baseMapper.selectList(wrapper);
        if(CollectionUtils.isNotEmpty(commentList)){
            //如果评论不为空，循环取出，存入集合
            for(Comment comment:commentList){
                String id=comment.getId();
                ids.add(id);
                //递归查询子评论下的子评论
                this.getIds(ids,id);
            }
        }
    }
}
